import React, { PureComponent, Fragment } from 'react';
import { connect } from 'dva';
import {
  Row,
  Col,
  Card,
  Form,
  Input,
  Select,
  Icon,
  Button,
  Dropdown,
  Menu,
  TimePicker,
  DatePicker,
  message,
  Divider,
} from 'antd';
import StandardTable from '@/components/StandardTable';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import UpdateForm from './createFrom';
import DescView from './descView';
import styles from '../UserManage.less';
import { powerBtnFunc } from '@/utils/utils';

const Option = Select.Option;
const FormItem = Form.Item;

/* eslint react/no-multi-comp:0 */
@connect(({ rewardModels, loading }) => ({
  rewardModels,
  loading: loading.models.rewardModels,
}))

@Form.create()
class DeptManage extends PureComponent {
  state = {
    modalVisible: false,
    updateModalVisible: false,
    lookDescView: false,
    selectedRows: {},
    formValues: {},
    pagination: {
      pageNo: 1,
      pageSize: 15,
    },
  };


  constructor(props) {
    super(props);
  }


  componentDidMount() {
    const { dispatch } = this.props;
    dispatch({
      type: 'rewardModels/fetch',
      payload: {},
    });

  }

  handleStandardTableChange = (pagination, filtersArg, sorter) => {
    const { dispatch } = this.props;
    const { formValues } = this.state;

    const filters = Object.keys(filtersArg).reduce((obj, key) => {
      const newObj = { ...obj };
      newObj[key] = getValue(filtersArg[key]);
      return newObj;
    }, {});
    this.setState({
      pagination: {
        pageNo: pagination.current,
        pageSize: 15,
      },
    });
    const params = {
      pageNo: pagination.current,
      pageSize: pagination.pageSize,
      ...formValues,
      ...filters,
    };
    if (sorter.field) {
      params.sorter = `${sorter.field}_${sorter.order}`;
    }

    dispatch({
      type: 'rewardModels/fetch',
      payload: params,
    });
  };
  //重置
  handleFormReset = () => {
    const { form, dispatch } = this.props;
    form.resetFields();
    this.setState({
      formValues: {},
    });
    dispatch({
      type: 'rewardModels/fetch',
      payload: {},
    });
  };


  handRemove = e => {
    const { dispatch } = this.props;
    const { pagination } = this.state;
    dispatch({
      type: 'rewardModels/remove',
      payload: {
        key: e.id,
      },
      callback: (res) => {
        if (res.code === 200) {
          message.success('删除成功');
          this.setState({
            selectedRows: [],
          });
          dispatch({
            type: 'rewardModels/fetch',
            payload: pagination,
          });
        } else {
          message.error(res.errMsg);

        }

      },
    });
  };

  handleSelectRows = rows => {
    this.setState({
      selectedRows: rows,
    });
  };
  //搜索
  handleSearch = e => {
    e.preventDefault();

    const { dispatch, form } = this.props;

    form.validateFields((err, fieldsValue) => {
      if (err) return;

      const values = {
        ...fieldsValue,
      };
      console.log('values', values);
      this.setState({
        formValues: values,
      });

      dispatch({
        type: 'rewardModels/fetch',
        payload: values,
      });
    });
  };
  //新建显示窗口
  handleModalVisible = flag => {
    this.setState({
      modalVisible: !!flag,
      updateModalVisible: !!flag,
      selectedRows: {},
    });
  };
  //修改
  handleUpdateModalVisible = (flag, record) => {
    console.log(!!flag);
    this.setState({
      updateModalVisible: !!flag,
      modalVisible: !flag,
      selectedRows: record,
      formVals: record,
    });
  };
  //查看
  handleLookDesc = (flag, record) => {
    console.log(record);
    const { dispatch } = this.props;
    this.setState({
      lookDescView: !!flag,
      selectedRows: record,
    }, () => {
      if (!!flag) {
        dispatch({
          type: 'rewardModels/getDeptDesc',
          payload: { id: record.id },
        });
      }
    });
  };
  //新建请求
  handleAdd = fields => {
    const { dispatch } = this.props;
    dispatch({
      type: 'rewardModels/add',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'rewardModels/fetch',
        });
        this.handleModalVisible(false);
      },
    });

  };
  //修改请求
  handleUpdate = fields => {
    const { pagination } = this.state;
    const { dispatch } = this.props;
    dispatch({
      type: 'rewardModels/update',
      payload: fields,
      callback: (response) => {
        dispatch({
          type: 'rewardModels/fetch',
          payload: pagination,
        });
        this.handleUpdateModalVisible(false, []);
      },
    });
  };

  renderSimpleForm() {
    const { form: { getFieldDecorator } } = this.props;
    return (
      <Form onSubmit={this.handleSearch} layout="inline">
        <Row gutter={{ md: 8, lg: 24, xl: 48 }}>
          <Col md={6} sm={24}>
            <FormItem label="时间">
              {getFieldDecorator('time')(<DatePicker placeholder="选择时间"
                                                     style={{ width: '100%' }}/>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
            <FormItem label="奖励类型">
              {getFieldDecorator('rewardType')(
                <Select placeholder='请选择奖励类型' style={{ width: '100%' }}>
                  <Option value={1}>首投</Option>
                  <Option value={2}>佣金</Option>
                </Select>,
              )}
            </FormItem>
          </Col>
          <Col md={6} sm={24}>
        <span className={styles.submitButtons}>
        <Button type="primary" htmlType="submit">
        查询
        </Button>
        <Button style={{ marginLeft: 8 }} onClick={this.handleFormReset}>
        重置
        </Button>

        </span>
          </Col>
        </Row>
      </Form>
    );
  }


  render() {
    const { rewardModels: { data, userList, deptDesc }, loading } = this.props;
    const { selectedRows, modalVisible, updateModalVisible, lookDescView } = this.state;

    const columns = [
      {
        title: '开始时间',
        dataIndex: 'startTime',
      },
      {
        title: '结束时间',
        dataIndex: 'endTime',
      },
      {
        title: '奖励类型',
        dataIndex: 'rewardType',
        render: val => <span>{val === 1 ? '首投' : '佣金'}</span>,
      },

      {
        title: '新手标',
        dataIndex: 'newHand',
        render: val => <span>{val === 1 ? '是' : '否'}</span>,
      },

      {
        title: '普通标',
        dataIndex: 'normal',
        render: val => <span>{val === 1 ? '是' : '否'}</span>,
      },
      {
        title: '债转标',
        dataIndex: 'debt',
        render: val => <span>{val === 1 ? '是' : '否'}</span>,
      },

      {
        title: '期限',
        dataIndex: 'rewardTerm',
      },
      {
        title: '发放类型',
        dataIndex: 'sendType',
        render: val => <span>{val === 1 ? '回款' : '按周'}</span>,
      },
      {
        title: '操作',
        render: (text, record) => (
          <Fragment>
            {powerBtnFunc('100118',
              [<a onClick={() => this.handleUpdateModalVisible(true, record)}>修改</a>,
                <Divider type="vertical"/>],
            )}
            {powerBtnFunc('100116',
              [<a onClick={() => this.handleLookDesc(true, record)}>查看</a>,
                <Divider type="vertical"/>],
            )}
            {powerBtnFunc('100119',
              <a onClick={() => this.handRemove(record)}>删除</a>)}

          </Fragment>
        ),
      },
    ];

    const parentMethods = {
      handleAdd: this.handleAdd,
      handleModalVisible: this.handleModalVisible,
    };
    const updateMethods = {
      handleUpdateModalVisible: this.handleUpdateModalVisible,
      handleUpdate: this.handleUpdate,
    };
    return (
      <PageHeaderWrapper title="奖励设置">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListForm}>{this.renderSimpleForm()}</div>
            <div className={styles.tableListOperator}>
              {powerBtnFunc('100117',
                <Button icon="plus" type="primary" onClick={() => this.handleModalVisible(true)}>
                  新建
                </Button>,
              )}
            </div>
            <StandardTable
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              rowKey={'id'}
              columns={columns}
              onSelectRow={this.handleSelectRows}
              onChange={this.handleStandardTableChange}
            />
          </div>
        </Card>
        {deptDesc
          ?
          <DescView handleLookDesc={this.handleLookDesc} selectedRows={deptDesc} lookDescView={lookDescView}/>
          :
          ''}
        <UpdateForm
          {...updateMethods}
          {...parentMethods}
          updateModalVisible={updateModalVisible}
          modalVisible={modalVisible}
          values={selectedRows}
          data={data}
        />

      </PageHeaderWrapper>
    );
  }
}

export default DeptManage;
